<template>
  <div class="basic">
    <el-dialog width="900px" :title="$t('修改头像')" :visible.sync="isShow" :close-on-click-modal="false">
      <div class="img_list">
        <div class="upload_img" v-if="applets_img">
          <img :src="applets_img" />
        </div>
        <el-upload
          :action=" protocol + '//cdb.workair.vip/operate/screenadv/fileUpload'"
          :headers="{ token, ocode }"
          name="img_file"
          :data="{ type: 'image' }"
          :file-list="fileList"
          :limit="1"
          :on-exceed="handleExceed"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :on-error="handleError"
          list-type="picture"
        >
          <el-button type="primary">{{$t('选择文件')}}</el-button>
        </el-upload>
        
      </div>
      <el-button class="submit_btn" type="primary" @click="submit">{{$t('提交')}}</el-button>
    </el-dialog>
  </div>
</template>

<script>
import util from "@/assets/js/util.js";
import { mapState } from "vuex";
export default {
  name: "changeAvatar",
  data() {
    return {
      isShow: false,
      protocol: window.location.protocol,
      fileList: [],
      applets_img: "",
      applets_imgId: "",
    };
  },
  props: {
    avatar: {
      type: String,
      default: ''
    },
  },
  computed: {
    ...mapState(["token", "ocode"]),
  },
  methods: {
    show() {
      this.isShow = true;
      this.fileList = []
      this.applets_img = this.avatar
    },
    submit() {
      util.$http('/user/avatar', {
        image: this.applets_imgId
      })
      .then(res=>{
        if(res.code == 1) {
          this.isShow = false;
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.$emit('hide', this.applets_img)
        }
      })
    },
    handleSuccess(response, file) {
      this.applets_imgId = response.msg;
      this.applets_img = response.path;
    },
    handleRemove() {
      this.applets_imgId = "";
      this.applets_img = "";
    },
    handleError(err) {
      this.$message({
        message: this.$t('上传失败'),
        type: 'warning'
      });
    },
    handleExceed() {
      this.$message({
        message: this.$t('只能上传一张'),
        type: 'warning'
      });
    },
  },
};
</script>

<style scoped>
.basic .img_list {
  max-width: 400px;
  margin-bottom: 30px;
}

.basic .img_list .upload_img {
  width: 200px;
  height: 200px;
  margin-bottom: 20px;
}
.basic .img_list img {
  width: 100%;
  height: 100%;
}
</style>
